package com.campus.utils;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

public class CaptchaUtil {
    private static final int WIDTH = 140;
    private static final int HEIGHT = 50;
    private static final int CODE_LENGTH = 4;
    private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    public static CaptchaInfo generateCaptcha() throws IOException {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        Random random = new Random();
        StringBuilder captchaCode = new StringBuilder();

        for (int i = 0; i < CODE_LENGTH; i++) {
            String charStr = String.valueOf(CHARSET.charAt(random.nextInt(CHARSET.length())));
            captchaCode.append(charStr);
            g.setColor(getRandomColor());
            g.setFont(new Font("Arial", Font.BOLD, 30));
            g.drawString(charStr, 20 + i * 30, 35);
        }

        for(int i = 0; i < 5; i++) {
            g.setColor(getRandomColor());
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        g.dispose();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        return new CaptchaInfo(captchaCode.toString(), "data:image/png;base64," + base64Image);
    }
    private static Color getRandomColor() {
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }

    @AllArgsConstructor
    @Data
    public static class CaptchaInfo {
        private String code;
        private String base64Image;
    }
}
